from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect

from bbs.MessageFormPost import MessagePostForm
from bbs.models import Message
import datetime

# 查询列表
def getMessage(request):
    posts = Message.objects.all()
    return render_to_response('archive.html', {'msgs': posts}, context_instance=RequestContext(request))

# 保存信息
def saveMessage(request):
    form = MessagePostForm(request.POST)
    if form.is_valid():
        time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        print(time)
        newmessage = Message(
            author=form.cleaned_data['author'],
            title=form.cleaned_data['title'],
            content=form.cleaned_data['content'],
            timestamp=time
        )
        # 将合法的表单数据保存到数据库
        newmessage.save()
        return HttpResponseRedirect('/bbs')  # 重定向到首页
    else:
        form = MessagePostForm()
        # 使用message_post_page.html模板显示表单
        return render_to_response('message_post_page.html', {'form': form}, context_instance=RequestContext(request))
